package com.gxuwz.prrs;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.gxuwz.prrs.bean.AppointmentRecord;
import com.gxuwz.prrs.bean.CheckRecord;
import com.gxuwz.prrs.bean.Notice;
import com.gxuwz.prrs.bean.UserInfo;
import com.gxuwz.prrs.constant.Constants;
import com.gxuwz.prrs.receiver.AlarmReceiver;
import com.gxuwz.prrs.service.impl.AppointmentRecordServiceImpl;
import com.gxuwz.prrs.service.impl.AuthServiceImpl;
import com.gxuwz.prrs.service.ServiceHolder;
import com.gxuwz.prrs.service.impl.CheckRecordServiceImpl;
import com.gxuwz.prrs.service.impl.NoticeServiceImpl;
import com.gxuwz.prrs.utils.NavigationUtils;
import com.gxuwz.prrs.utils.NotificationHelper;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


public class MainActivity extends AppCompatActivity {

	private final ServiceHolder serviceholder = ServiceHolder.getInstance();
	TextView timeCountDown;
	TextView usingPianoNo;
	Button checkOut;
	CheckRecordServiceImpl checkRecordService = serviceholder.getBean(CheckRecordServiceImpl.class);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		NavigationUtils.setRedirectBottom(this);
		TextView lastNotice = findViewById(R.id.last_notice);
		NoticeServiceImpl noticeService = serviceholder.getBean(NoticeServiceImpl.class);
		Notice notice = noticeService.lastNotice();
		if(notice != null){
			lastNotice.setText(notice.getTitle());
			lastNotice.setOnClickListener(view -> {
				Bundle bundle = new Bundle();
				bundle.putString(Constants.TITLE, notice.getTitle());
				bundle.putString(Constants.CONTENT, notice.getContent());
				bundle.putString(Constants.NOTICE_TIME, notice.getNoticeTime());
				NavigationUtils.redirectToNoticeDetailActivity(MainActivity.this, bundle);
			});
		}
		ImageView toPiano = findViewById(R.id.to_piano_rooms);
		toPiano.setOnClickListener(view -> {
			NavigationUtils.redirectToPianoRoomsActivity(MainActivity.this, null);
		});
		ImageView toAppointmentRecords = findViewById(R.id.to_appointment_records);
		toAppointmentRecords.setOnClickListener(view -> NavigationUtils.redirectToAppointmentRecordsActivity(MainActivity.this, null));
		ImageView checkin = findViewById(R.id.check_in);
		checkin.setOnClickListener(view -> {
			IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
			intentIntegrator.initiateScan();
		});
		timeCountDown = findViewById(R.id.time_count_down);
		usingPianoNo = findViewById(R.id.using_piano_no);
		checkOut = findViewById(R.id.check_out);
		LinearLayout checkOutArea = findViewById(R.id.check_out_area);
		setTimer(checkOutArea);
	}

	private void setTimer(LinearLayout checkOutArea){
		checkOutArea.setVisibility(View.INVISIBLE);
		checkOutArea.setClickable(false);
		checkOutArea.setEnabled(false);
		AppointmentRecordServiceImpl appointmentRecordService = serviceholder.getBean(AppointmentRecordServiceImpl.class);
		AppointmentRecord appointmentRecord = appointmentRecordService.getUpcomingAppointment();
		if (appointmentRecord != null) {
			String status = appointmentRecord.getStatus();
			String appointmentTime = appointmentRecord.getAppointmentTime();
			String[] split = appointmentTime.split("-");
			if ("正在使用".equals(status)) {
				checkOutArea.setVisibility(View.VISIBLE);
				checkOutArea.setClickable(true);
				checkOutArea.setEnabled(true);
				usingPianoNo.setText(String.valueOf(appointmentRecord.getPianoRoomNo()));
				checkOut.setOnClickListener(view -> {
					CheckRecord checkRecord = new CheckRecord();
					checkRecord.setPianoRoomId(appointmentRecord.getPianoRoomId());
					checkRecord.setStatus("签退");
					Boolean b = checkRecordService.check(checkRecord);
					if (b) {
						Toast.makeText(MainActivity.this, "签退成功", Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(MainActivity.this, "签退失败，请重试", Toast.LENGTH_LONG).show();
					}
					NavigationUtils.redirectToMainActivity(MainActivity.this, null);
				});
				LocalTime endTime = LocalTime.parse(split[1], DateTimeFormatter.ofPattern(Constants.TIME_PATTERN));
				LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
				now = now.plusHours(8);
				LocalTime nowTime = now.toLocalTime();
				LocalTime countDownTime = endTime.minusHours(nowTime.getHour()).minusMinutes(nowTime.getMinute());
				new CountDownTimer(getMillis(countDownTime), 1000) {
					public void onTick(long millisUntilFinished) {
						timeCountDown.setText(getTime(millisUntilFinished));
						if (millisUntilFinished / 1000 / 60 % 60 == 10 && millisUntilFinished / 1000 % 60 == 0) {
							try {
								CompletableFuture.runAsync(() -> {
									NotificationHelper.sendNotification(MainActivity.this, "签退通知", "本次练习距离结束还有10分钟，可以签退了",
											"checkout", "签退通知渠道", 1, NotificationManager.IMPORTANCE_HIGH, R.drawable.piano);
								}).get();
							} catch (Exception e) {
								throw new RuntimeException(e);
							}
						}
					}
					public void onFinish() {
						timeCountDown.setText("本次练习已结束，请及时签退");
					}
				}.start();
			} else if ("已预约".equals(status)) {
				SharedPreferences sharedPreferences = getSharedPreferences("appointment", Context.MODE_PRIVATE);
				boolean isTaskSet = sharedPreferences.getBoolean("setTask", false);
				if (!isTaskSet) {
					AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
					Intent intent = new Intent(this, AlarmReceiver.class);
					PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
					String time = appointmentRecord.getAppointmentDate() + " " + split[0];
					LocalDateTime startTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
					startTime = startTime.minusMinutes(10);
					Instant instant = startTime.atZone(ZoneId.systemDefault()).toInstant();
					long milliseconds = instant.toEpochMilli();
					System.out.println("已经设置定时任务");
					alarmManager.set(AlarmManager.RTC_WAKEUP, milliseconds, pendingIntent);
					SharedPreferences.Editor editor = sharedPreferences.edit();
					editor.putBoolean("setTask", true);
					editor.apply();
				}
			}
		}
	}

	private Long getMillis(LocalTime localTime) {
		long hour = localTime.getHour();
		long minute = localTime.getMinute();
		long second = localTime.getSecond();
		return ((hour * 60L + minute) * 60L + second) * 1000L;
	}

	private String getTime(Long millis) {
		long secondCount = millis / 1000;
		long seconds = secondCount % 60;
		long minusCount = secondCount / 60;
		long minus = minusCount % 60;
		long hour = minusCount / 60;
		return hour + ":" + minus + ":" + seconds;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
		IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
		if (result != null) {
			if (result.getContents() == null) {
				Toast.makeText(this, "取消扫描", Toast.LENGTH_LONG).show();
			} else {
				CheckRecord checkRecord = new CheckRecord();
				checkRecord.setPianoRoomId(Long.valueOf(result.getContents()));
				checkRecord.setStatus("签到");
				Boolean b = checkRecordService.check(checkRecord);
				if (b) {
					Toast.makeText(this, "签到成功", Toast.LENGTH_LONG).show();
					NavigationUtils.redirectToMainActivity(this, null);
				} else {
					Toast.makeText(this, "签到失败，请确认你是否预约了该琴房此时段的使用", Toast.LENGTH_LONG).show();
				}
			}
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
	}
}
